import 'package:dio/dio.dart';
import 'package:flutter_app/network/Code.dart';
import 'package:flutter_app/utils/toast_utils.dart';

import 'ResultData.dart';

///
/// 拦截器，用于网络数据返回加工预处理
///

class ResponseInterceptors extends Interceptor {
  ///响应前
  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    RequestOptions option = response.requestOptions;
    // print("---------response.data----------");
    // print(response.data);
    // print("---------response.data end----------");
    try {
      if (option.contentType != null && option.contentType!.contains("text")) {
        response.data = ResultData(response.data, true, Code.SUCCESS);
        handler.next(response);
      }

      ///一般只需要处理200的情况，300、400、500保留错误信息，外层为http协议定义的响应码
      if (response.statusCode == 200 || response.statusCode == 201) {
        ///内层需要根据公司实际返回结构解析，一般会有code，data，msg字段

        var status = response.data["status"];
        if (status == null) {
          response.data =  ResultData(response.data, true, Code.SUCCESS, headers: response.headers);
          handler.next(response);
          return;
        }
        if (status == Code.SUCCESS) {
          response.data =  ResultData(response.data, true, Code.SUCCESS, headers: response.headers);
          handler.next(response);

          // print("----------response.data----------");
          // print(response.data);
          // print("----------response.data end----------");

          return;
        } else {
          response.data =  ResultData(response.data, false, Code.SUCCESS, headers: response.headers);
          handler.next(response);
          return;
        }
      } else if (response.statusCode == 404) {
        toast.show("网络异常");
      }
    } catch (e) {
      print("ResponseError====" + e.toString() + "****" + option.path);

      response.data = ResultData(response.data, false, response.statusCode!, headers: response.headers);
      handler.next(response);
      return;
    }

    response.data = ResultData(response.data, false, response.statusCode!, headers: response.headers);
    handler.next(response);
  }
}
